import APIS from "../api";

export const RequestPlugin = {
  install(vm, opt) {
    if (!jingweiAxios) return;

    const isDev = process.env.NODE_ENV === "development";
    const token = document.cookie.replace(/(?:(?:^|.*;\s*)token\s*\=\s*([^;]*).*$)|^.*$/, "$1");
    const http = new jingweiAxios.create(APIS, {
      baseURL: isDev ? "" : "/",
      headers: {
        post: {
          ["Content-Type"]: "application/json"
        },
        put: {
          ["Content-Type"]: "application/json"
        },
        Authorization: token
      }
    });

    const request = http.axiosInstance;

    request.interceptors.response.use(
      res => {
        if (res && res.status == 200) {
          let { data, headers } = res;
          // 流媒体
          if (headers["content-type"] === "application/octet-stream") return data;
          if (data.code === 0 && data.message === "ok") {
            //请求成功
            return data.data;
          } else {
            if (data.code === 401 || data.code === 403) {
              // token 过期或失效
              location.href = location.origin + "/#/login";
            }
            // 请求失败，抛出失败信息
            Vue.prototype.$message({
              message: `请求出错：${data.message}`,
              type: "error"
            });
            throw data.message;
          }
        }
      },
      err => {
        Vue.prototype.$message({
          message: `请求出错：${err}`,
          type: "error"
        });
        throw err;
      }
    );
    request.interceptors.request.use(config => {
      const token = document.cookie.replace(/(?:(?:^|.*;\s*)token\s*\=\s*([^;]*).*$)|^.*$/, "$1");
      config.headers.Authorization = token;
      return config;
    });
    vm.prototype.$http = http;
  }
};
